package com.medicine.utils.base;

import com.medicine.common.utils.JsonUtil;
import com.medicine.common.utils.MathUtil;
import com.medicine.common.utils.ValidateUtil;
import com.medicine.utils.Result;
import org.apache.commons.io.FileUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author chenbo
 * 
 */
public class BaseController {

	protected final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected HttpSession session;

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;


	/**
	 * 将对象转换成JSON字符串，并响应回前台
	 * 
	 * @param object
	 *            需要序列化的对象
	 *            如果是基础数据类型请先转换转换成字符串
	 */
	protected void writeJson(Object object) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(JsonUtil.bean2Json(object));
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error("",e);
		}
	}

	/***
	 * 将普通字符串数据响应回前台
	 * 
	 * @param data
	 * 
	 *            如果是基础数据类型请先转换转换成字符串
	 */
	protected void writeJson(String data) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(data);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error("",e);
		}
	}

	/**
	 * 获取参数
	 * 
	 * @param para
	 * @return
	 */
	protected String getParameter(String para) {
		return request.getParameter(para);
	}

	/**
	 * 获取视图对象
	 * 
	 * @return
	 */
	protected ModelAndView getModelAndView() {
		return new ModelAndView();
	}

	/**
	 * 下载文件对象
	 * 
	 * @param file				文件下载路径
	 * @param downloadFielName	文件名称  为空时，取文文件存储名称
	 * @return					文件下载流对象
	 */
	protected ResponseEntity<byte[]> download(File file,String downloadFielName){
        ResponseEntity<byte[]> responEntity = null;
		try {
			downloadFielName = downloadFielName == null ? file.getName() : downloadFielName;
			downloadFielName = new String(downloadFielName.getBytes("UTF-8"),"ISO-8859-1");
			HttpHeaders headers = new HttpHeaders();
	        headers.setContentDispositionFormData("attachment", downloadFielName);
	        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	        responEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
		} catch (UnsupportedEncodingException e) {
			logger.error("",e);
		} catch (IOException e) {
			logger.error("",e);
		}
        return responEntity;
	}
	
	
	/**
	 * 文件上传
	 * 
	 * @param request		spring封装后requet对象
	 * @param filePath		文件存储路径
	 * @param fileName		文件名称  （可以为空，如果为空，默认去上传的文件名加时间前缀）
	 * @return				返回上传成功的文件全路径名
	 */
	protected List<String> upload(HttpServletRequest request,String filePath,String fileName){
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        List<String> files = new ArrayList<String>();
		try{
	        if(multipartResolver.isMultipart(request)){  
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){ 
	                    String name = file.getOriginalFilename();  
	                    if(name.trim() !=""){
	                    	fileName = ValidateUtil.empty(fileName) ? MathUtil.random() + "_" + name : fileName;
	                        String path = filePath + fileName;  
	                        File localFile = new File(path);  
	                        file.transferTo(localFile);
	                        files.add(path);
	                    }
	                }  
	            }  
	        }  
        }catch(Exception e){
        	throw new RuntimeException(e);
        }
		return files;
	}
	
	/**
	 * 获取结果对象
	 * 
	 * @return
	 */
	protected Result getResult() {
		return new Result();
	}

	/**
	 * 获取IP
	 * 
	 * @return
	 */
	protected String getIp() {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}
}
